<template>
  <div class="DbInfoBar-outer">DbInfoBar-{{ curDbInfo.name }}--{{ curDbInfo.version }}</div>
</template>

<script>
import connection from './jsstore_con';

export default {
  name: 'DbInfoBar',
  data() {
    return {
      curDbInfo: {
        name: 'jsStore_Radar',
        tables: [],
        version: 1,
      },
    };
  },
  methods: {
    async checkJsStore() {
      const srcDbList = await connection.getDbList();
      const jsStoreList = srcDbList.filter(item => {
        return item.name.startsWith('jsStore_');
      });
      if (jsStoreList.length === 0) {
        const result = await connection.initDb(this.curDbInfo);
        if (result) {
          this.$Message.success('数据库创建成功: jsStore_Radar');
        }
      } else {
        const tmpInfo = jsStoreList[0];
        this.curDbInfo.version = tmpInfo.version;
      }
    },

    async updateDb(fileName, param) {
      const dbInfo = await connection.openDb(this.curDbInfo.name, this.curDbInfo.version);
      const tableName = fileName.split('-')[2];
      const columns = {};
      param.forEach(item => {
        const colObj = {};
        if (item.dataType) {
          colObj.dataType = item.dataType;
        }
        if (item.notNull) {
          colObj.notNull = true;
        }
        if (item.primaryKey) {
          colObj.primaryKey = true;
        }
        columns[item.name] = colObj;
      });
      dbInfo.tables = dbInfo.tables.filter(item => {
        return item.name !== 'JsStore_Meta';
      });
      dbInfo.tables.push({
        name: tableName,
        columns: columns,
      });
      dbInfo.version++;
      const result = await connection.initDb(dbInfo);
      if (result) {
        this.$Message.success('表添加成功: ' + tableName);
      }
    },

    async importData(fileName, param) {
      const tableName = fileName.split('-')[2];
      const result = await connection.insert({
        into: tableName,
        values: param,
      });
      if (result) {
        this.$Message.success('数据导入成功: ' + tableName + ', ' + result);
      }
    },
  },
  mounted() {
    this.checkJsStore();
  },
};
</script>

<style scoped>
.DbInfoBar-outer {
  padding: 0 8px;
  margin-bottom: 16px;
}
</style>
